/**
 * 宝宝信息管理API服务
 * 提供宝宝档案的增删改查功能
 */

import { get, post, put, del } from '@/utils/request';

// 宝宝信息接口 - 与Supabase BabyProfile保持一致
export interface BabyInfo {
  id?: string;
  user_id?: string;
  name: string;
  gender: 'male' | 'female';
  birth_date: string; // 与数据库字段名保持一致
  weight?: number; // 当前体重
  height?: number; // 当前身高
  preferences?: Record<string, any>; // 存储额外信息如头像、出生体重等
  created_at?: string;
  updated_at?: string;
  
  // 兼容性字段（用于前端显示）
  birthDate?: string;
  avatar?: string;
  birthWeight?: number;
  birthHeight?: number;
  currentWeight?: number;
  currentHeight?: number;
  notes?: string;
  createdAt?: string;
  updatedAt?: string;
}

// 成长记录接口
export interface GrowthRecord {
  id?: string;
  babyId: string;
  date: string;
  weight?: number;
  height?: number;
  notes?: string;
  createdAt?: string;
}

// 宝宝列表查询参数
export interface BabyListParams {
  page?: number;
  pageSize?: number;
  keyword?: string;
}

// 宝宝列表响应
export interface BabyListResponse {
  list: BabyInfo[];
  total: number;
  page: number;
  pageSize: number;
}

/**
 * 获取宝宝列表
 * @param params 查询参数
 * @returns Promise<BabyListResponse>
 */
export const getBabyList = (params?: BabyListParams) => {
  return get<BabyListResponse>('/baby/list', params);
};

/**
 * 获取宝宝详情
 * @param id 宝宝ID
 * @returns Promise<BabyInfo>
 */
export const getBabyDetail = (id: string) => {
  return get<BabyInfo>(`/baby/${id}`);
};

/**
 * 创建宝宝档案
 * @param data 宝宝信息
 * @returns Promise<BabyInfo>
 */
export const createBaby = (data: Omit<BabyInfo, 'id' | 'createdAt' | 'updatedAt'>) => {
  return post<BabyInfo>('/baby/create', data);
};

/**
 * 更新宝宝信息
 * @param id 宝宝ID
 * @param data 更新的宝宝信息
 * @returns Promise<BabyInfo>
 */
export const updateBaby = (id: string, data: Partial<BabyInfo>) => {
  return put<BabyInfo>(`/baby/${id}`, data);
};

/**
 * 删除宝宝档案
 * @param id 宝宝ID
 * @returns Promise<void>
 */
export const deleteBaby = (id: string) => {
  return del<void>(`/baby/${id}`);
};

/**
 * 上传宝宝头像
 * @param file 图片文件
 * @returns Promise<string> 返回图片URL
 */
export const uploadBabyAvatar = (file: File | string) => {
  // 这里应该实现实际的文件上传逻辑
  // 可以使用uni.uploadFile或者其他上传方式
  return new Promise<string>((resolve, reject) => {
    uni.uploadFile({
      url: process.env.NODE_ENV === 'development' 
        ? 'http://localhost:3000/api/upload/avatar' 
        : 'https://your-api-domain.com/api/upload/avatar',
      filePath: file as string,
      name: 'avatar',
      header: {
        'Authorization': `Bearer ${uni.getStorageSync('token') || ''}`
      },
      success: (res) => {
        try {
          const data = JSON.parse(res.data);
          if (data.code === 200) {
            resolve(data.data.url);
          } else {
            reject(new Error(data.message || '上传失败'));
          }
        } catch (error) {
          reject(new Error('上传响应解析失败'));
        }
      },
      fail: (error) => {
        reject(error);
      }
    });
  });
};

/**
 * 获取宝宝成长记录
 * @param babyId 宝宝ID
 * @returns Promise<GrowthRecord[]>
 */
export const getBabyGrowthRecords = (babyId: string) => {
  return get<GrowthRecord[]>(`/baby/${babyId}/growth-records`);
};

/**
 * 添加成长记录
 * @param data 成长记录数据
 * @returns Promise<GrowthRecord>
 */
export const addGrowthRecord = (data: Omit<GrowthRecord, 'id' | 'createdAt'>) => {
  return post<GrowthRecord>('/baby/growth-record', data);
};

/**
 * 更新成长记录
 * @param id 记录ID
 * @param data 更新的记录数据
 * @returns Promise<GrowthRecord>
 */
export const updateGrowthRecord = (id: string, data: Partial<GrowthRecord>) => {
  return put<GrowthRecord>(`/baby/growth-record/${id}`, data);
};

/**
 * 删除成长记录
 * @param id 记录ID
 * @returns Promise<void>
 */
export const deleteGrowthRecord = (id: string) => {
  return del<void>(`/baby/growth-record/${id}`);
};

/**
 * 计算宝宝年龄
 * @param birthDate 出生日期
 * @returns 年龄字符串
 */
export const calculateBabyAge = (birthDate: string): string => {
  if (!birthDate) return '';
  
  const birth = new Date(birthDate);
  const now = new Date();
  const diffTime = Math.abs(now.getTime() - birth.getTime());
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
  
  if (diffDays < 30) {
    return `${diffDays}天`;
  } else if (diffDays < 365) {
    const months = Math.floor(diffDays / 30);
    const days = diffDays % 30;
    return days > 0 ? `${months}个月${days}天` : `${months}个月`;
  } else {
    const years = Math.floor(diffDays / 365);
    const months = Math.floor((diffDays % 365) / 30);
    return months > 0 ? `${years}岁${months}个月` : `${years}岁`;
  }
};

/**
 * 获取宝宝发育标准数据
 * @param gender 性别
 * @param ageInMonths 月龄
 * @returns 发育标准数据
 */
export const getBabyDevelopmentStandards = (gender: 'male' | 'female', ageInMonths: number) => {
  return get<any>('/baby/development-standards', { gender, ageInMonths });
};

/**
 * 分析宝宝发育情况
 * @param babyId 宝宝ID
 * @returns 发育分析报告
 */
export const analyzeBabyDevelopment = (babyId: string) => {
  return get<any>(`/baby/${babyId}/development-analysis`);
};

/**
 * 获取宝宝喂养建议
 * @param babyId 宝宝ID
 * @returns 喂养建议
 */
export const getBabyFeedingAdvice = (babyId: string) => {
  return get<any>(`/baby/${babyId}/feeding-advice`);
};

/**
 * 获取宝宝疫苗接种计划
 * @param babyId 宝宝ID
 * @returns 疫苗接种计划
 */
export const getBabyVaccinationPlan = (babyId: string) => {
  return get<any>(`/baby/${babyId}/vaccination-plan`);
};

/**
 * 记录宝宝日常活动
 * @param data 活动记录数据
 * @returns Promise<any>
 */
export const recordBabyActivity = (data: {
  babyId: string;
  activityType: 'feeding' | 'sleep' | 'diaper' | 'play' | 'other';
  startTime: string;
  endTime?: string;
  notes?: string;
  amount?: number; // 喂养量等
  unit?: string; // 单位
}) => {
  return post<any>('/baby/activity', data);
};

/**
 * 获取宝宝活动记录
 * @param babyId 宝宝ID
 * @param date 日期
 * @returns 活动记录列表
 */
export const getBabyActivities = (babyId: string, date?: string) => {
  return get<any[]>(`/baby/${babyId}/activities`, { date });
};

/**
 * 生成宝宝成长报告
 * @param babyId 宝宝ID
 * @param startDate 开始日期
 * @param endDate 结束日期
 * @returns 成长报告
 */
export const generateBabyGrowthReport = (babyId: string, startDate: string, endDate: string) => {
  return get<any>(`/baby/${babyId}/growth-report`, { startDate, endDate });
};